'use strict';
/**
 * Created by FreezeSoul on 2015/10/23.
 */
define([
    "app/core/base",
    "jquery",
    "underscore",
    'JSONParse',
    'loglevel',
    "echarts"
], function (Chart, $, _, JSON, log, ec) {

    //TODO:自定义组件属性
    var property = {
        //标题文本
        TitleText: undefined,
        //标题颜色
        TitleColor: undefined,
        //副标题文本
        SubTitleText: undefined,
        //副标题颜色
        SubTitleColor: undefined,
        //背景色
        BackgroundColor: undefined,
        //轴字体颜色
        AxisTextColor: undefined,
        //图例字体颜色
        LegendTextColor: undefined,
        //序列颜色
        SeriesColors: undefined,
        //序列设置{SeriesIndex:0,SeriesType:'bar',SeriesStack:'',LabelPosition:'',IsAreaStyle:false}
        SeriesOption: undefined,
        //标题位置
        TitlePosition: undefined,
        //图例位置
        LegendPosition: undefined,
        //坐标值位置
        WhichAxisIsValue: undefined,
        //坐标网格
        WhichAxisShowGrid: undefined,
        //X轴留白，主要应用在面积图
        XboundaryGap: undefined,
        //Y轴留白，主要应用在面积图
        YboundaryGap: undefined,
        //是否显示工具栏
        IsShowToolbox: undefined,
        //需要针对组件映射属性至组件Option
        MapOption: function (option) {
            var _this = this;

            //标题
            if (this.TitleText) {
                $.extend(true, option, {title: {text: _this.TitleText}});
            }

            //标题颜色
            if (this.TitleColor) {
                $.extend(true, option, {title: {textStyle: {color: _this.TitleColor}}});
            }

            //副标题
            if (this.SubTitleText) {
                $.extend(true, option, {title: {subtext: _this.SubTitleText}});
            }

            //副标题颜色
            if (this.SubTitleColor) {
                $.extend(true, option, {title: {subtextStyle: {color: _this.SubTitleColor}}});
            }

            //背景色设置
            if (this.BackgroundColor) {
                option.backgroundColor = this.BackgroundColor;
            }

            //图例字体颜色
            if (this.LegendTextColor) {
                $.extend(true, option, {legend: {textStyle: {color: _this.LegendTextColor}}});
            }

            //轴字体边框颜色，统一设置，如果需要单独设置，请用Option自行设置
            if (this.AxisTextColor) {

                $.each(option.xAxis, function (i, xAxis) {
                    $.extend(true, xAxis, {
                        axisLine: {
                            lineStyle: {
                                color: _this.AxisTextColor
                            }
                        },
                        axisTick: {
                            lineStyle: {
                                color: _this.AxisTextColor
                            }
                        },
                        axisLabel: {
                            textStyle: {
                                color: _this.AxisTextColor
                            }
                        },
                        nameTextStyle: {
                            color: _this.AxisTextColor
                        }
                    });
                });

                $.each(option.yAxis, function (i, yAxis) {
                    $.extend(true, yAxis, {
                        axisLine: {
                            lineStyle: {
                                color: _this.AxisTextColor
                            }
                        },
                        axisTick: {
                            lineStyle: {
                                color: _this.AxisTextColor
                            }
                        },
                        axisLabel: {
                            textStyle: {
                                color: _this.AxisTextColor
                            }
                        },
                        nameTextStyle: {
                            color: _this.AxisTextColor
                        }
                    });
                });
            }

            //标题位置设置
            if (this.TitlePosition) {
                $.extend(true, option, {
                    title: {
                        x: _this.TitlePosition.split(',')[0],
                        y: _this.TitlePosition.split(',')[1]
                    }
                });
            }

            //图例位置设置
            if (this.LegendPosition) {
                $.extend(true, option, {
                    legend: {
                        x: _this.LegendPosition.split(',')[0],
                        y: _this.LegendPosition.split(',')[1]
                    }
                });
            }

            //序列颜色
            if (this.SeriesColors
                && this.SeriesColors.length > 0) {
                option.color = this.SeriesColors;
            }

            //值在哪个轴
            if (this.WhichAxisIsValue) {
                var where = this.WhichAxisIsValue;
                $.each(option.xAxis, function (i, xAxis) {
                    xAxis.type = where == "yAxis" ? "category" : "value";
                });
                $.each(option.yAxis, function (i, yAxis) {
                    yAxis.type = where == "xAxis" ? "category" : "value";
                });
            }

            //哪个轴有网格
            if (this.WhichAxisShowGrid) {
                $.each(option.xAxis, function (i, xAxis) {
                    if (!xAxis.splitLine) xAxis.splitLine = {};
                    if (_this.WhichAxisShowGrid == "yAxis&xAxis"
                        || _this.WhichAxisShowGrid == "xAxis") {
                        xAxis.splitLine.show = true;
                    } else {
                        xAxis.splitLine.show = false;
                    }
                });
                $.each(option.yAxis, function (i, yAxis) {
                    if (!yAxis.splitLine) yAxis.splitLine = {};
                    if (_this.WhichAxisShowGrid == "yAxis&xAxis"
                        || _this.WhichAxisShowGrid == "yAxis") {
                        yAxis.splitLine.show = true;
                    } else {
                        yAxis.splitLine.show = false;
                    }
                });
            }

            //序列类型与堆积
            if (this.SeriesOption) {
                $.each(this.SeriesOption, function (i, seriesoption) {
                    var series = _.findWhere(option.series, {name: seriesoption.SeriesName});
                    if (series) {
                        if (seriesoption.SeriesType) {
                            series.type = seriesoption.SeriesType;
                        }
                        if (seriesoption.SeriesStack) {
                            series.stack = seriesoption.SeriesStack;
                        }
                        if (seriesoption.LabelPosition) {
                            $.extend(true, series, {
                                itemStyle: {
                                    normal: {
                                        label: {
                                            show: true,
                                            position: seriesoption.LabelPosition
                                        }
                                    }
                                }
                            });
                        }
                        if (seriesoption.SeriesType == 'line' && seriesoption.IsAreaStyle) {
                            series.areaStyle = {normal: {}};
                        }
                    }
                });
            }

            //轴边距
            $.each(option.xAxis, function (i, xAxis) {
                xAxis.boundaryGap = (_this.XboundaryGap === true);
            });

            $.each(option.yAxis, function (i, yAxis) {
                yAxis.boundaryGap = (_this.YboundaryGap === true);
            });

            //是否显示工具栏
            if (this.IsShowToolbox) {
                $.extend(true, option, {
                    toolbox: {
                        show: true,
                        feature: {
                            magicType: {show: true, type: ['line', 'bar', 'stack', 'tiled']},
                            restore: {show: true},
                            saveAsImage: {show: true}
                        }
                    }
                });
            }
        }
    };

    var bar = Chart.extend({
        constructor: function (layout) {
            this._layout = layout;
            this._chart = null;
            this._option = {
                Binding: [],
                Events: [],
                Extend: $.extend({}, property),
                Option: {
                    title: {
                        x: 'center',
                        y: 'top',
                        text: '某地区蒸发量和降水量',
                        subtext: '纯属虚构'
                    },
                    tooltip: {
                        trigger: 'axis'
                    },
                    legend: {
                        x: 'center',
                        y: 'bottom',
                        data: ['蒸发量', '降水量']
                    },
                    toolbox: {
                        show: false
                    },
                    calculable: false,
                    xAxis: [
                        {
                            type: 'category',
                            data: ['1月', '2月', '3月', '4月', '5月', '6月', '7月', '8月', '9月', '10月', '11月', '12月']
                        }
                    ],
                    yAxis: [
                        {
                            type: 'value'
                        }
                    ],
                    series: [
                        {
                            name: '蒸发量',
                            type: 'bar',
                            data: [2.0, 4.9, 7.0, 23.2, 25.6, 76.7, 135.6, 162.2, 32.6, 20.0, 6.4, 3.3]
                        },
                        {
                            name: '降水量',
                            type: 'bar',
                            data: [2.6, 5.9, 9.0, 26.4, 28.7, 70.7, 175.6, 182.2, 48.7, 18.8, 6.0, 2.3]
                        }
                    ]
                }
            };
        },
        init: function (element) {
            try {
                this._chart = ec.init(element, null, {
                    renderer: 'canvas'
                });
                this._bindEvent();
            } catch (e) {
                log.error(e);
            }
        },
        //TODO:需要重写的部分
        _bindEvent: function () {
            var _this = this;
            this._chart.on("click", function (param) {
                if (_this._layout
                    && _this._layout.navigate
                    && _this._option.Events
                    && _this._option.Events.length > 0) {

                    var registerEvent = _.findWhere(_this._option.Events, {Event: "SeriesClick"});
                    if (registerEvent) {
                        var pageId = registerEvent.PageId;
                        var params = registerEvent.Params;
                        var args = [];
                        var dParam = _.findWhere(params, {Value: "Dimension"});
                        if (dParam && dParam.ParamName) {
                            args.push({
                                ParamName: dParam.ParamName,
                                ParamValue: param.name
                            });
                        }
                        var mParam = _.findWhere(params, {Value: "Measure"});
                        if (mParam && mParam.ParamName) {
                            args.push({
                                ParamName: mParam.ParamName,
                                ParamValue: param.value
                            });
                        }
                        var sParam = _.findWhere(params, {Value: "SeriesName"});
                        if (sParam && sParam.ParamName) {
                            args.push({
                                ParamName: sParam.ParamName,
                                ParamValue: param.seriesName
                            });
                        }
                        _this._layout.navigate(pageId, args);

                    }
                    param.event.event.preventDefault();
                }
            });
        },
        example: function () {
            try {
                this._chart.setOption(this._option.Option, true);
            } catch (e) {
                log.error(e);
            }
        },
        _readProperty: function () {
            try {
                if (!this._option.Extend) return;
                var propertyCopy = $.extend(true, {}, property);
                $.extend(true, propertyCopy, this._option.Extend);
                propertyCopy.MapOption(this._option.Option);
            } catch (e) {
                log.error(e);
            }
        },
        //TODO:需要重写的部分
        _bindData: function (data) {
            var tables = data;
            var _this = this;

            //清理工作
            this._option.Option.legend.data = [];
            $.each(this._option.Option.xAxis, function (i, xAxis) {
                if (xAxis.type == "category") {
                    xAxis.data = [];
                } else {
                    delete xAxis.data;
                }
            });
            $.each(this._option.Option.yAxis, function (i, yAxis) {
                if (yAxis.type == "category") {
                    yAxis.data = [];
                } else {
                    delete yAxis.data;
                }
            });

            var categoryAxis = this._option.Option.xAxis[0].type == "category" ? this._option.Option.xAxis[0] : this._option.Option.yAxis[0];

            //绑定数据
            $.each(this._option.Extend.SeriesOption, function (i, series) {
                if (series.DataSetCode && series.DimensionCode && series.MeasureCode) {
                    var table = tables[series.DataSetCode];

                    var binding = _.findWhere(_this._option.Binding, {DataSetCode: series.DataSetCode});
                    var dimension = _.findWhere(binding.Dimensions, {Code: series.DimensionCode}).Column;
                    var measure = _.findWhere(binding.Measures, {Code: series.MeasureCode}).Column;
                    _this._option.Option.legend.data.push(series.SeriesName);
                    var data = [];
                    $.each(table, function (j, row) {
                        if (categoryAxis.data.indexOf(row[dimension]) == -1) {
                            categoryAxis.data.push(row[dimension]);
                        }
                        data.push(row[measure]);
                    });
                    if (_this._option.Option.series.length >= i + 1) {
                        _this._option.Option.series[i].name = series.SeriesName;
                        _this._option.Option.series[i].data = data;
                    } else {
                        _this._option.Option.series.push({
                            name: series.SeriesName,
                            type: series.SeriesType,
                            data: data
                        })
                    }
                }
            });
            //移除手工设置的
            if (this._option.Option.series.length > this._option.Extend.SeriesOption.length) {
                this._option.Option.series.splice(this._option.Extend.SeriesOption.length, this._option.Option.series.length - this._option.Extend.SeriesOption.length);
            }
        },
        setData: function (data) {
            try {
                this._readProperty();

                if (data
                    && this._option.Binding
                    && this._option.Binding.length > 0
                    && this._option.Extend
                    && this._option.Extend.SeriesOption.length > 0
                    && _.every(this._option.Extend.SeriesOption, function (series) {
                        return series.DataSetCode && series.DimensionCode && series.MeasureCode;
                    })) {

                    this._bindData(data);

                    this._readProperty();
                }
                this._chart.setOption(this._option.Option, true);
            } catch (e) {
                log.error(e);
            }
        },
        setOption: function (option) {
            try {
                return this._option = $.extend(true, {}, option);
            } catch (e) {
                log.error(e);
            }
        },
        getOption: function () {
            try {
                this._readProperty();
            } catch (e) {
                log.error(e);
            }
            return this._option;
        },
        setTheme: function (theme) {
            try {
                this._chart.setTheme(theme);
            } catch (e) {
                log.error(e);
            }
        },
        resize: function () {
            try {
                this._chart.resize();
            } catch (e) {
                log.error(e);
            }
        },
        showLoading: function () {
            try {
                if (this._layout && this._layout.showLoading) {
                    this._layout.showLoading(this);
                }
            } catch (e) {
                log.error(e);
            }
        },
        hideLoading: function () {
            try {
                if (this._layout && this._layout.hideLoading) {
                    this._layout.hideLoading(this);
                }
            } catch (e) {
                log.error(e);
            }
        },
        dispose: function () {
            try {
                this._chart.dispose();
            } catch (e) {
                log.error(e);
            }
        },
        getElement: function () {
            return null;
        },
        getChart: function () {
            return this._chart;
        }
    });

    return bar;
});
